<?php

namespace App\Http\Controllers\Frontend\User;

use App\Http\Controllers\Frontend\FrontendController;
use App\Http\Resources\Frontend\ApiResource;
use App\Models\ProjectShare;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ShareController extends FrontendController
{

    public function createMany(Request $request)
    {
        $post = $request->post();
        if(empty($post['share_many'])){
            return new ApiResource('验证失败',0);
        }
        $res = json_decode($post['share_many'],true);
        $flag = true;
        $insertData = [];
        if(!empty($res) && is_array($res)){
            foreach($res as $one){
                $validator = Validator::make($one,[
                    'project_id' => 'required|int',
                    'permission_id' => 'required|int',
                    'type' => 'required|int',
                    'target' => 'required|int',
                ]);
                if($validator->fails()){

                    $flag = false;
                    break;
                }
                $insertOne = $one;
                $insertOne['user_id'] = auth()->id();
                $insertOne['created_at'] = date('Y-m-d H:i:s',time());
                $insertOne['updated_at'] = date('Y-m-d H:i:s',time());
                $insertData[] = $insertOne;
            }
        }else{
            $flag = false;
        }

        if($flag){
            //批量新增
            $insertRes = DB::table('project_share')->insert($insertData);
            if(!$insertRes){
                return new ApiResource('新增失败',0);
            }
            return new ApiResource();
        }else{
            return new ApiResource('验证失败',0);
        }

    }

    //修改
    public function update(Request $request,$id)
    {
        $model = ProjectShare::find($id);
        $post = $request->post();
        $validate = Validator::make($post,[
            'permission_id' => 'required|int',
        ]);
        if($validate->fails()){
            return new ApiResource('验证失败',0);
        }
        $model->permission_id = $post['permission_id'];
        if($model->save()){
            return new ApiResource();
        }else{
            return new ApiResource('修改失败',0);
        }
    }
}
